/**
 *  *2010-4-17 上午09:42:50  add 
 */
package com.base.myproject.client.busi.ccode;

import java.util.Date;
import java.util.HashMap;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.busi.service.AddFinace_acc;
import com.base.myproject.client.jdbc.DataSet;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.BaseResource;
import com.base.myproject.client.system.Env;
import com.base.myproject.client.tools.CommandSyncContainer;
import com.base.myproject.client.tools.CommandSyncReturnObject;
import com.base.myproject.client.tools.CommandSyncsql;
import com.base.myproject.client.ui.BaseFormPanel;
import com.base.myproject.client.ui.celleditor.BaseComboBoxForm;
import com.base.myproject.client.ui.codenamemap.CodeNameMapFactory;
import com.extjs.gxt.ui.client.Style.Orientation;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.Field;
import com.extjs.gxt.ui.client.widget.form.TextArea;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.Validator;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;
import com.extjs.gxt.ui.client.widget.layout.TableData;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.Label;

/**
 * 新会员信息 注意与CcodePanel同步
 * 
 * @author Administrator 2010-4-17 javazgw@gmail.com
 */
public class NewCCode implements Listener<BaseEvent> {

	Dialog d = new Dialog();
	BaseFormPanel w;

	TextField<String> ccode_t;
	TextField<String> cardno_t;
	TextField<String> icode_t;
	TextField<String> cname_t;
	TextField<String> password_t = new TextField<String>();
	TextField<String> passwordc_t = new TextField<String>();
	Button addfinace = new Button("充值");
	public NewCCode() {
		init();
	}

	void init() {
		initWidget();
	}

	private void initWidget() {
		initmainpanel();
		addfinace.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE.addfinance()));
		d.setHeading("添加新会员");
		d.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE
				.contact24()));
		d.setLayout(new RowLayout(Orientation.HORIZONTAL));

		d.setButtons(Dialog.YESNO);
		d.getButtonById(Dialog.YES).setText("添加新会员");
		d.getButtonById(Dialog.NO).setText("关闭");
		d.getButtonById(Dialog.YES).setIcon(
				AbstractImagePrototype
						.create(BaseResource.INSTANCE.contact24()));

		d.getButtonById(Dialog.YES).addListener(Events.Select, this);
		d.getButtonById(Dialog.NO).addListener(Events.Select, this);

		d.add(w, new RowData(1, 1));

		d.setSize(607, 373);
		// d.setAutoHeight(true);
		// d.setAutoWidth(true);

		store._LoadComplete();

	}

	private void setdefault() {

		DateTimeFormat activeFormat = DateTimeFormat
				.getFormat("yyyy-M-d H:mm:ss");
		activeFormat.format(new Date());

		store.addDefault("ccodetype", "1");
		store.addDefault("createbcode", Env.getEnvbcode());
		store.addDefault("createbname", Env.getEnvname());
		store.addDefault("createdate", activeFormat.format(new Date()));

	}

	BaseStore<BusiObject> store;

	BaseStore<BusiObject> getStore() {
		store = new BaseStore<BusiObject>();
		// store.addBaseStoreListener( EventType.ROW_ADDED,
		// getBasestoreListener());

		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		type.addField("icode");
		type.addField("ccode");
		type.addField("cname");
		type.addField("s_cardno");
		type.addField("s_sex");
		type.addField("s_edu");
		type.addField("s_birid");
		type.addField("s_mobil");
		type.addField("s_idno");
		type.addField("s_mark");
		type.addField("password");

		type.addField("createbname");
		type.addField("createdate");
		type.addField("updatebname");
		type.addField("updatedate");
		type.addField("ccodetype");
		type.addField("rbcode");
		
		type.getField("s_cardno").setType(String.class);
		type.getField("s_sex").setType(Integer.class);

		type.getField("s_edu").setType(String.class);
		type.getField("s_birid").setType(Date.class);

		type.getField("s_mobil").setType(String.class);
		type.getField("s_idno").setType(String.class);
		type.getField("s_mark").setType(String.class);
		type.getField("password").setType(String.class);
		StoreInfo info = new StoreInfo();
		info.setTablename("ccode");
		info.setKeyname(new String[] { "icode" });
		store.setType(type);
		store.setStoreinfo(info);
		setdefault();
		HashMap hm = new HashMap();

		BusiObject modeldata = new BusiObject(hm);

		store.add(modeldata, true, false);

		return store;
	}

	/***
	 * 主窗口
	 */
	void initmainpanel() {

		w = new BaseFormPanel(getStore());
		w.setHeaderVisible(false);
		Label cardno_l = new Label("卡号:");
		cardno_l.setWidth("50");
		Label cname_l = new Label("名字:");
		cname_l.setWidth("50");
		Label sex_l = new Label("性别:");
		sex_l.setWidth("50");
		Label edu_l = new Label("学历:");
		Label bird_l = new Label("出生日期:");

		Label mobil_l = new Label("手机号:");
		Label idno_l = new Label("身份证号:");
		Label mark_l = new Label("备注:");
		

		cardno_t = new TextField<String>();
		cardno_t.setAllowBlank(false);
		cardno_t.addListener(Events.Change, this);
		cname_t = new TextField<String>();
		cname_t.setAllowBlank(false);
		
//		passwordc_t.setAllowBlank(false);
//		password_t.setAllowBlank(false);
//		
		// TextField<String> sex_t = new TextField<String>();
		// BaseGridEditor sex_t= CodeNameMapFactory.aa();
		BaseComboBoxForm<BaseModelData> sex_t = CodeNameMapFactory
				.createSexInput_F();
		TextField<String> edu_t = new TextField<String>();
		// CodeNameMapFactory codenamemap = new CodeNameMapFactory();

		// BaseGridEditor<String> edu_t =codenamemap.createSexInput_G();

		// createBocdeInput_F
		DateField bird_t = new DateField();
		bird_t.setAutoWidth(true);

		bird_t.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-M-d H:mm:ss"));
		TextField<String> mobil_t = new TextField<String>();
		mobil_t.setAllowBlank(false);
		TextField<String> idno_t = new TextField<String>();

		TextArea mark_t = new TextArea();
		mark_t.setSize(420, 40);
		//TextField<String> password_t = new TextField<String>();

		password_t.setPassword(true);
		passwordc_t.setPassword(true);
		// password_t.setToolTip("将光标放到此处，并由会员录入自己的密码");
		ccode_t = new TextField<String>();
		// ccode_t.setEnabled(false);
		ccode_t.setVisible(false);
		icode_t = new TextField<String>();
		icode_t.setVisible(false);

		cardno_t.setName("s_cardno");
		cname_t.setName("cname");
		password_t.setName("password");

		sex_t.setName("s_sex");
		edu_t.setName("s_edu");
		bird_t.setName("s_birid");
		mobil_t.setName("s_mobil");
		idno_t.setName("s_idno");
		mark_t.setName("s_mark");
		ccode_t.setName("ccode");
		icode_t.setName("icode");
		//password_t.setName("password");

		TableLayout tl = new TableLayout(4);
		tl.setWidth("600");
		w.setLayout(tl);
		TableData td = new TableData();
		td.setColspan(1);
		// td.setWidth("2000");
		td.setMargin(100);
		td.setPadding(5);
		td.setRowspan(1);

		TableData td2 = new TableData();
		td2.setColspan(3);
		// td.setWidth("2000");
		td2.setMargin(100);
		td2.setPadding(5);
		td2.setRowspan(1);

		w.add(cardno_l, td);
		w.add(cardno_t, td);
		w.add(cname_l, td);
		w.add(cname_t, td);

		w.add(mobil_l, td);
		w.add(mobil_t, td);
		w.add(sex_l, td);
		w.add(sex_t, td);
		
		w.add(new Label("密码："), td);
		w.add(password_t, td);
		w.add(new Label("重新录入密码："), td);
		w.add(passwordc_t, td);
		
		
		w.add(edu_l, td);
		w.add(edu_t, td);
		w.add(bird_l, td);
		w.add(bird_t, td);

		w.add(idno_l, td);
		w.add(idno_t, td);
		w.add(new Label(""), td);
		w.add(new Label(""), td);
		w.add(mark_l, td);
		w.add(mark_t, td2);
		
		w.add(new Label("销售人员："), td);
		BaseComboBoxForm<BaseModelData> cbf= createBcode_filter();
		cbf.setName("rbcode");
		cbf.setAllowBlank(false);
		w.add(cbf, td2);
		
		
		w.add(ccode_t, td);
		w.add(icode_t, td);
		w.setBottomComponent(addfinace);
		
		addfinace.addListener(Events.Select, this);
		addfinace.setEnabled(false);
		w.inited();

		// w.setAutoHeight(true);
		// w.setAutoWidth(true);
		// w.setSize(661, 300);

		cardno_t.addListener(Events.Change, this);
		cname_t.addListener(Events.Change, this);

		// mobil_t.addListener(Events.Change, this);

		cardno_t.setValidateOnBlur(true);
		cname_t.setValidateOnBlur(true);
	}

	public void show() {
		d.show();
	}

	@Override
	public void handleEvent(BaseEvent be) {
		// TODO Auto-generated method stub

		if (be.getType().equals(Events.Select)) {
			//会员充值
			if (be.getSource().equals(addfinace)) {
				AddFinace_acc addfinace_acc = new AddFinace_acc();
				addfinace_acc.setIsnew(0);
				addfinace_acc.showDialog();
			} 
			if (be.getSource().equals(d.getButtonById(Dialog.NO))) {
				close();
			} else if (be.getSource().equals(d.getButtonById(Dialog.YES))) {
				passwordc_t.clearInvalid();
				
				String passwordc=(passwordc_t.getValue()==null?"":passwordc_t.getValue() ); 
				String password=(password_t.getValue()==null?"":password_t.getValue() ); 
				if((!passwordc.equals(password)))
				{
					
					passwordc_t.markInvalid("两次录入密码不一致");
				MessageBox.alert("提示", "两次密码录入不一致", null);
				return;
				
				}
				if (w.isValid()) {
					
					 CommandSyncContainer list  = new CommandSyncContainer();
					 CommandSyncsql commandsql = new CommandSyncsql();
					 
					// 保存
					commandsql.getV().addAll(store._trySave(0));
					// 更新ccode
					/**
					 * 不得已才如此操作，因为ccode的ccode字段是与其他操作管理的字段，和ccodepanel里的做法一直，
					 * 默认与icode同值
					 */
					GWT.log("update ccode set ccode =icode where s_cardno='"
							+ cardno_t.getValue() + "' and cname='"
							+ cname_t.getValue() + "'", null);
					commandsql.getV().add(
							"update ccode set ccode =icode where s_cardno='"
									+ cardno_t.getValue() + "' and cname='"
									+ cname_t.getValue() + "'");
					
					list.add(commandsql);

					final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
							.create(com.base.myproject.client.tools.GreetingService.class);
					greetingService.SendCommandSync(list,
							new AsyncCallback<CommandSyncReturnObject>() {
								public void onFailure(Throwable caught) {
									Window.alert("网络连接不稳定，请稍后重试！");
								}

								public void onSuccess(
										CommandSyncReturnObject cyro) {

									System.out.println("成功："
											+ cyro.getMessage() + cyro.isB()
											+ cyro.getRetrunstr());
									if (cyro.isB()) {
										Info.display("", "保存成功", "");
										addfinace.setEnabled(true);
										//close();
									} else {
										MessageBox.alert("错误", "保存错误！"
												+ cyro.getMessage(), null);
									}
								}
							});
					 
					//store.trySave(0);
					d.getButtonById(Dialog.YES).setEnabled(false);
				} else
					MessageBox.alert("禁止", "请检查录入是否正确！", null);

			}

		} else if (be.getType().equals(Events.Change)) {
			if (be.getSource().equals(cardno_t)) {

				final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
						.create(com.base.myproject.client.tools.GreetingService.class);
				greetingService.getDataSet(
						"select count(*) as c from ccode where s_cardno='"
								+ cardno_t.getValue() + "'",
						new AsyncCallback<DataSet>() {

							@Override
							public void onFailure(Throwable caught) {

							}

							@Override
							public void onSuccess(DataSet result) {

								if (Integer.parseInt(result.getValue(0, "c")) > 0) {
									Validator v = new Validator() {

										@Override
										public String validate(Field<?> field,
												String value) {

											return "已经存在相同卡号的用户";
										}
									};

									cardno_t.setValidator(v);

								} else {
									cardno_t.setValidator(null);
								}
								cardno_t.validate();
							}

						});

			} else if (be.getSource().equals(cname_t)) {

				final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
						.create(com.base.myproject.client.tools.GreetingService.class);
				greetingService.getDataSet(
						"select count(*) as c from ccode where cname='"
								+ cname_t.getValue() + "'",
						new AsyncCallback<DataSet>() {

							@Override
							public void onFailure(Throwable caught) {

							}

							@Override
							public void onSuccess(DataSet result) {

								if (Integer.parseInt(result.getValue(0, "c")) > 0) {
									Validator v = new Validator() {

										@Override
										public String validate(Field<?> field,
												String value) {

											return "已经存在相同名字的用户";
										}
									};

									cname_t.setValidator(v);
								} else {
									cname_t.setValidator(null);

								}

								cname_t.validate();
							}

						});

			}
//			else if (name.equals("s_cardno")) {
//				ccode_t.setFireChangeEventOnSetValue(true);
//				ccode_t.setValue(icode_t.getValue());
//				ccode_t.setFireChangeEventOnSetValue(false);
//			} 
		}
	}

	public void close() {

		w = null;

		ccode_t = null;
		cardno_t = null;
		icode_t = null;
		cname_t = null;
		d.hide();
	}
	BaseComboBoxForm<BaseModelData> createBcode_filter()
	{
		
		BaseStore<BaseModelData> base_filter;
			ModelType type = new ModelType();
			type.setRoot("records");
			type.setRecordName("record");
			type.setTotalName("totle");
			type.addField("code");
			type.addField("name");
			StoreInfo info = new StoreInfo();
			info.setTablename("bcode");
			info.setNeedAllRow("no");
			info.setForcenolimit("true");
			info.setSql("select bcode as code,bname as name from bcode where bcode is not null and bname is not null and systemid in (select systemid from bcode where bcode= '"+Env.getEnvbcode()+"')");
			//info.setSql("select bcode as code,bname as name from bcode where bcode is not null and bname is not null ");
			base_filter = new BaseStore<BaseModelData>(type,info);
	
		BaseComboBoxForm<BaseModelData> bcbf = new BaseComboBoxForm<BaseModelData>(base_filter);
		return bcbf;
	}
}
